package com.boarsoft.boar.demo.order.roller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.boarsoft.boar.demo.order.biz.PocOrderBiz;
import com.boarsoft.boar.demo.order.biz.PocTrxMessageBiz;
import com.boarsoft.boar.demo.order.entity.PocOrder;
import com.boarsoft.boar.demo.order.entity.PocTrxMessage;
import com.boarsoft.common.Util;
import com.boarsoft.common.util.RandomUtil;
import com.boarsoft.message.bean.Message;
import com.boarsoft.message.bean.MessageEntity;
import com.boarsoft.message.bean.MessageQueryParam;
import com.boarsoft.message.store.MessageRoller;

public class OrderRoller implements MessageRoller {
	private static final Logger log = LoggerFactory.getLogger(OrderRoller.class);

	private static final String dateFormate = "yyyy-MM-dd HH:mm:ss";

	@Autowired
	PocOrderBiz orderBiz;

	@Autowired
	PocTrxMessageBiz trxMessageBiz;

	public void init() throws Exception {
		log.info("进入roller初始化...");
	}

	@Override
	public String append(Message m) throws Exception {
		// log.info("进入了Append...");
		// log.info("Received product transaction ==> {}", m.getContent());

		String id = m.getId();
		if (Util.strIsEmpty(id)) {
			id = RandomUtil.genUUID();
			m.setId(id);
		}

		PocOrder pm = (PocOrder) m.getContent();

		PocTrxMessage trxMessage = new PocTrxMessage();
		trxMessage.setMessageId(id);
		trxMessage.setOrderId((int) pm.getOrderId());
		trxMessage.setTenantId((int) pm.getTenantId());
		trxMessage.setMessageStatus(String.valueOf(m.getStatus()));
		trxMessage.setMessageTried(m.getTried());
		trxMessage.setMessageMemo("订单消息持久化");
		trxMessage.setCreateTime(new SimpleDateFormat(dateFormate).format(new Date()));
		trxMessage.setModifyTime(new SimpleDateFormat(dateFormate).format(new Date()));

		trxMessageBiz.trxSave(trxMessage.getTenantId(), trxMessage);

		return id;
	}

	@Override
	public void close() {
		// TODO Auto-generated method stub
	}

	@Override
	public long update(Message m, String memo) throws Exception {
		log.info("进入了设置消息发送成功或失败的Update(带message)...");

		long lastTime = new Date().getTime();
		PocOrder pm = (PocOrder) m.getContent();

		PocTrxMessage trxMessage = trxMessageBiz.findById(((int) pm.getTenantId()), m.getId());
		if (trxMessage != null) {
			log.info("订单消息：{}", trxMessage);
		} else {
			log.error("未找到订单消息");
			return lastTime;
		}

		trxMessage.setMessageStatus(String.valueOf(m.getStatus()));
		trxMessage.setMessageTried(m.getTried());
		trxMessage.setMessageMemo(memo);
		trxMessage.setModifyTime(new SimpleDateFormat(dateFormate).format(new Date()));

		trxMessageBiz.update(trxMessage.getTenantId(), trxMessage);

		return lastTime;
	}

	@Override
	public long update(String id, short status, int tried, String memo) throws Exception {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public long update(String id, String recipient, int tried, short status, String memo) throws Exception {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public MessageEntity read(String id) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<MessageEntity> reload(Date before, Date after, short status, int limit) throws Exception {
		// log.info("进入了重发的reload...");

		List<MessageEntity> lt = new LinkedList<MessageEntity>();
		List<PocTrxMessage> trxList0 = new LinkedList<PocTrxMessage>();
		List<PocTrxMessage> trxList1 = new LinkedList<PocTrxMessage>();

		// 查询未发送的消息
		String reloadSql = " and messageStatus = '?'";

		List<PocTrxMessage> trxMsgList0 = (List<PocTrxMessage>) trxMessageBiz.findAll(0, reloadSql, 1, 10);
		List<PocTrxMessage> trxMsgList1 = (List<PocTrxMessage>) trxMessageBiz.findAll(1, reloadSql, 1, 10);

		trxMsgList0.addAll(trxMsgList1);

		long now = new Date().getTime();
		int i = 0;
		for (PocTrxMessage trxMsg : trxMsgList0) {

			Message m = new Message();
			m.setTarget("productTransaction");
			m.addRecipient("productTransactionSvc");

			// 查询订单信息，再次组装消息
			PocOrder order = orderBiz.findById(trxMsg.getTenantId(), trxMsg.getOrderId());
			if (order != null) {
				m.setId(trxMsg.getMessageId());
				m.setContent(order);
			} else {
				log.error("Message {} is null", trxMsg.getMessageId());
				trxMsg.setMessageStatus(String.valueOf(Message.STATUS_FAILED));
				trxMsg.setModifyTime(new SimpleDateFormat(dateFormate).format(new Date()));
				trxMsg.setMessageMemo("Message is null");
				if (getDataSource(trxMsg.getTenantId()) == 0) {
					trxList0.add(trxMsg);
				} else {
					trxList1.add(trxMsg);
				}
				continue;
			}

			trxMsg.setMessageStatus(String.valueOf(Message.STATUS_SENT));
			trxMsg.setModifyTime(new SimpleDateFormat(dateFormate).format(new Date()));
			trxMsg.setMessageMemo("Message is queued");
			if (getDataSource(trxMsg.getTenantId()) == 0) {
				trxList0.add(trxMsg);
			} else {
				trxList1.add(trxMsg);
			}
			// 不再持久化
			MessageEntity me = new MessageEntity(m, this);
			me.setAddTime(now);
			me.setLastTime(now);
			me.setStatus(Message.STATUS_QUEUED);
			me.setTried(trxMsg.getMessageTried());
			me.setMemo("Message is queued");

			i++;
			log.info("增加了几次消息：" + i);
			lt.add(me);
		}

		if (trxList0.size() != 0) {
			trxMessageBiz.batchUpdate(0, trxList0);
		}
		if (trxList1.size() != 0) {
			trxMessageBiz.batchUpdate(1, trxList1);
		}

		return lt;

	}

	@Override
	public int truncate(Date before) throws Exception {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int getPageSize() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public List<MessageEntity> query(MessageQueryParam mqp) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Map<String, Object>> count(MessageQueryParam mqp) {
		// TODO Auto-generated method stub
		return null;
	}

	public int getDataSource(int tenantId) {
		return tenantId % 2;
	}
}